#include "MaterialCutParser.h"

#include "DoubleParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

MaterialCutParser::MaterialCutParser(
    DoubleParser *&_depthParser
    , DoubleParser *&_plusTolParser
    , DoubleParser *&_minusTolParser
):    m_depthParser(_depthParser)
    , m_plusTolParser(_plusTolParser)
    , m_minusTolParser(_minusTolParser)
{

}

bool MaterialCutParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new MaterialCut());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("depth")))
    {
        data = reader->attributes().value(QStringLiteral("depth"));
        if (!m_depthParser->parse(reader, data))
            return false;
        m_result->depth = m_depthParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("depth: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("plusTol")))
    {
        data = reader->attributes().value(QStringLiteral("plusTol"));
        if (!m_plusTolParser->parse(reader, data))
            return false;
        m_result->plusTol = m_plusTolParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("plusTol: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("minusTol")))
    {
        data = reader->attributes().value(QStringLiteral("minusTol"));
        if (!m_minusTolParser->parse(reader, data))
            return false;
        m_result->minusTol = m_minusTolParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("minusTol: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

MaterialCut *MaterialCutParser::result()
{
    return m_result.take();
}

}